import { defineStore } from "pinia";
import { loginApi, getUser } from "@/api/user";
import { wsClient } from "@/util/websocket";

interface UserState {
  token: string | null;
  user: {
    id: number;
    username: string;
    nickname: string;
    avatar: string;
  } | null;
}

export const useAuthStore = defineStore("auth", {
  state: (): UserState => {
    const token = localStorage.getItem("token");
    const userStr = localStorage.getItem("user");
    const user = userStr ? JSON.parse(userStr) : null;

    return {
      token: token || "",
      user: user,
    };
  },

  getters: {
    isAuthenticated(): boolean {
      return !!this.token;
    },
  },

  actions: {
    async login(username: string, password: string): Promise<boolean> {
      try {
        const response = await loginApi({ username, password });

        if (response.data.code === 200) {
          const userData = response.data.data;
          this.$state.token = userData.token;
          this.$state.user = {
            id: userData.id,
            username: userData.username,
            nickname: userData.nickname,
            avatar: userData.avatar,
          };

          localStorage.setItem("token", userData.token);
          localStorage.setItem("user", JSON.stringify(this.user));
          wsClient.connect();
          return true;
        }
        return false;
      } catch (error) {
        console.error("Login failed:", error);
        return false;
      }
    },

    async checkAuth(): Promise<boolean> {
      if (!this.token) return false;

      try {
        const response = await getUser();

        if (response.data.code === 200) {
          const userData = response.data.data;
          this.$state.user = {
            id: userData.id,
            username: userData.username,
            nickname: userData.nickname,
            avatar: userData.avatar,
          };
          localStorage.setItem("user", JSON.stringify(this.user));
          return true;
        }
        return false;
      } catch (error) {
        this.$state.token = null;
        this.$state.user = null;
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        return false;
      }
    },

    logout() {
      this.$state.token = null;
      this.$state.user = null;
      wsClient.disconnect();
    },

    setToken(token: string) {
      this.token = token;
      localStorage.setItem("token", token);
    },

    clearToken() {
      this.token = "";
      localStorage.removeItem("token");
    },

    updateUserAvatar(avatarUrl: string) {
      if (this.user) {
        this.user.avatar = avatarUrl;
        localStorage.setItem("user", JSON.stringify(this.user));
      }
    },
  },
});
